<template>
  <div class="follow-record-page">
    <!-- 顶部操作区 -->
    <div class="header">
      <el-button type="primary" @click="handleWriteFollow">写跟进</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>

    <!-- 写跟进表单 -->
    <div class="write-area" v-if="showWriteArea">
      <el-input
          v-model="followContent"
          type="textarea"
          placeholder="请输入跟进内容"
          rows="4"/>
      <el-button type="primary" @click="handlePublish" style="margin-top: 12px">发布</el-button>
    </div>

    <!-- 跟进记录时间线 -->
    <div class="record-timeline">
      <div v-for="(date, dateIndex) in uniqueDates" :key="dateIndex" class="timeline-group">
        <div class="date-title">{{ date }}</div>
        <el-timeline>
          <el-timeline-item
              v-for="(record, recordIndex) in filteredRecords(date)"
              :key="record.followId"
              :timestamp="record.time"
              placement="top"
          >
            <template #dot>
              <div class="custom-dot">{{ currentRole }}</div>
            </template>
            <div class="timeline-item-content">
              <div class="meta">
                <div class="role-tag" :class="record.role">{{ record.role }}</div>
                <div class="info">
                  <span class="name">{{ record.createBy }}</span>
                  <span class="time">{{ record.time }}</span>
                </div>
              </div>
              <div class="content">{{ record.followName }}</div>
              <div class="right-actions">
                <el-button type="text" @click="handleViewDetail(record)">跟进记录</el-button>
                <el-dropdown trigger="click">
                  <i class="el-icon-more"></i>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item>操作1</el-dropdown-item>
                      <el-dropdown-item>操作2</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
      <div class="no-more" v-if="followRecords.length === 0">没有更多跟进记录</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElButton, ElInput, ElTimeline, ElTimelineItem, ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus';
import { selectByOrderId, publishFollow } from '/@/api/order/follow';
import {useUserInfo} from '/@/stores/userInfo';
// 定义与后端对齐的跟进记录类型（字段对应后端 FollowRecord）
interface FollowRecord {
  followId: undefined;
  orderId: number;
  followName: ''; // 后端存储内容的字段
  createBy: string; // 创建人
  createTime: string; // 后端返回的 LocalDateTime 字符串
  guideId: number;
  // 前端字段
  date: string;
  time: string;
  role: string; // 根据 guideId
}

// 初始化变量
const router = useRouter();
const route = useRoute();
const followRecords = ref<FollowRecord[]>([]);
const followContent = ref('');
const showWriteArea = ref(false);

// 从路由参数动态获取 orderId
const orderId = computed(() => {
  const id = route.params.orderId;
  return id ? Number(id) : null; // 转换为数字类型
});

//获得当前用户角色
const userStore =useUserInfo();
const currentRole = computed(()=>{
  return userStore.userInfos?.roles || '未知角色';
})

// 页面加载时获取跟进记录
onMounted(async () => {
  if (!orderId.value) {
    ElMessage.error('缺少订单ID，无法加载跟进记录');
    return;
  }
  try {
    const res = await selectByOrderId(orderId.value);
    // 后端返回的是 R<List<FollowRecord>>，需从 data 提取数据
    if (res.code === 0 && res.data) {
      // 格式化时间为前端需要的 date 和 time
      followRecords.value = res.data.map((item: any) => {
        const createTime = new Date(item.createTime); // 解析后端时间字符串
        return {
          ...item,
          date: createTime.toLocaleDateString(),
          time: createTime.toLocaleTimeString(),
          role: item.guideId
        };
      });
    }
  } catch (error) {
    ElMessage.error('获取跟进记录失败');
  }
});

// 发布跟进内容
const handlePublish = async () => {
  if (!followContent.value.trim()) {
    ElMessage.warning('请输入跟进内容');
    return;
  }
  if (!orderId.value) {
    ElMessage.error('缺少订单ID，无法发布');
    return;
  }

  try {
    const requestData = {
      followName: followContent.value, // 对应后端 followName 字段
      orderId: orderId.value, // 动态传递订单ID
      createBy: '地陪',
    };

    // 调用发布接口
    const publishRes = await publishFollow(requestData);
    if (publishRes.code === 0) {
      ElMessage.success('发布成功');
      // 重新获取最新跟进记录
      const res = await selectByOrderId(orderId.value);
      if (res.code === 0 && res.data) {
        followRecords.value = res.data.map((item: any) => {
          const createTime = new Date(item.createTime);
          return {
            ...item,
            date: createTime.toLocaleDateString(),
            time: createTime.toLocaleTimeString(),
            role: item.guideId
          };
        });
      }
      followContent.value = '';
      showWriteArea.value = false;
    } else {
      ElMessage.error(publishRes.msg || '发布失败');
    }
  } catch (error) {
    ElMessage.error('发布失败');
  }
};

//返回订单页面
const handleBack = () => {
  router.push('/order/orders/index');
};

// 切换写跟进区域显示
const handleWriteFollow = () => {
  showWriteArea.value = !showWriteArea.value;
};

// 日期分组逻辑
const uniqueDates = computed(() => {
  const dates = new Set(followRecords.value.map(item => item.date));
  return Array.from(dates).sort((a, b) => new Date(b).getTime() - new Date(a).getTime()); // 倒序排列
});

// 根据日期过滤记录
const filteredRecords = (date: string) => {
  return followRecords.value
      .filter(item => item.date === date)
      .sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime()); // 时间倒序
};

// 查看详情
const handleViewDetail = (record: FollowRecord) => {
  // 可跳转详情页：router.push(`/follow-detail/${record.followId}`)
};
</script>

<style scoped>
/* 样式保持不变 */
.follow-record-page {
  padding: 20px;
  background: #fff;
  min-height: calc(100vh - 64px);
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.write-area {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}
.record-timeline {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
}
.timeline-group {
  margin-bottom: 20px;
}
.date-title {
  font-weight: bold;
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
}
.el-timeline {
  margin-left: 20px;
}
.timeline-item-content {
  background: #fff;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}
.meta {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  overflow: hidden;
}

::v-deep .custom-dot {
  width: auto !important;
  height: auto !important;
  padding: 4px 8px !important;
  border-radius: 4px !important;
  background-color: #409eff !important; /* 蓝色背景 */
  color: #fff !important; /* 白色文字 */
  font-size: 14px !important;
  border: none !important; /* 去除默认边框 */
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

/* 可选：隐藏组件默认的 dot（防止冲突） */
::v-deep .el-timeline-item__dot {
  display: none !important;
}
.role-tag {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  font-size: 14px;
  background-color: #409eff;
}
.info {
  display: flex;
  flex-direction: column;
}
.name {
  font-weight: bold;
  margin-bottom: 2px;
}
.time {
  font-size: 12px;
  color: #999;
}
.content {
  line-height: 1.6;
  margin-bottom: 8px;
}
.right-actions {
  align-self: flex-end;
  display: flex;
  align-items: center;
}
.right-actions .el-button {
  margin-right: 10px;
}
</style>
